package com.es.app.controller;

import com.es.app.dao.BookDao;
import com.es.app.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.StringQuery;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/es")
public class EsController {

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    BookDao dao;

    @RequestMapping("/adddao")
    public void saveDao(){
        Book book = new Book();
        book.setId(2);
        book.setBook_name("水浒传");
        book.setBook_price("10.0");
        dao.save(book);
    }

    @RequestMapping("/getdao")
    public void getDao(){
        Iterable<Book> books = dao.findAll();
        Iterator<Book> bookIterator = books.iterator();
        while (bookIterator.hasNext()){
            Book book = bookIterator.next();
            System.out.println(book.toString());
        }
    }
    @RequestMapping("/getdaoOne")
    public void getDaoById(String book_name){
        List<Book> books = dao.findByBook_name(book_name);
        for (Book b : books){
            System.out.println(b.toString());
        }
    }





    /**
     * 添加
     * */
    @RequestMapping("/add")
    public void demoSave (){
        Book book = new Book();
        book.setId(1);
        book.setBook_name("三国演义");
        book.setBook_price("10.0");

        IndexQuery indexQuery = new IndexQueryBuilder()
                .withId(book.getId().toString())
                .withObject(book)
                .build();

        //存入索引，返回文档id
        String documentId = elasticsearchTemplate.index(indexQuery);
        System.out.println(documentId);
    }
    /**
     * 查找
     * */
    @RequestMapping("/get")
    public void demoGet(){
        String json = "{\n" +
                             "        \"match\" : {\n" +
                            "            \"book_name\" : \"三国演义\"\n" +
                             "        }\n" +
                            "    }";
        StringQuery query = new StringQuery(json);
        query.addIndices("test");
        query.addTypes("news");

        List<Book> books = elasticsearchTemplate.queryForList(query,Book.class);
        if(books.size()>0){
            for(Book b : books){
                System.out.println(b.toString());
            }
        }
    }
}
